{% extends "base.html" %}

{% block title %}管理后台 - Excel2User{% endblock %}

{% block extra_css %}
<style>
    .dashboard-container {
        max-width: 800px;
        width: 95%;
    }
    
    .dashboard-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 30px;
        flex-wrap: wrap;
        gap: 10px;
    }
    
    .logout-btn {
        background: #dc3545;
        color: white;
        padding: 8px 16px;
        border: none;
        border-radius: 6px;
        text-decoration: none;
        font-size: 14px;
        transition: background 0.3s;
    }
    
    .logout-btn:hover {
        background: #c82333;
    }
    
    .upload-section {
        background: #f8f9fa;
        border-radius: 10px;
        padding: 25px;
        margin-bottom: 30px;
    }
    
    .upload-section h3 {
        color: #333;
        margin-bottom: 15px;
        display: flex;
        align-items: center;
        gap: 10px;
    }
    
    .file-input-wrapper {
        position: relative;
        display: inline-block;
        width: 100%;
        margin-bottom: 15px;
    }
    
    .file-input {
        position: absolute;
        opacity: 0;
        width: 100%;
        height: 100%;
        cursor: pointer;
    }
    
    .file-input-display {
        display: block;
        padding: 12px 15px;
        border: 2px dashed #667eea;
        border-radius: 8px;
        background: white;
        text-align: center;
        cursor: pointer;
        transition: all 0.3s;
    }
    
    .file-input-display:hover {
        border-color: #764ba2;
        background: #f8f9ff;
    }
    
    .file-info {
        margin-top: 10px;
        padding: 10px;
        background: #e9ecef;
        border-radius: 6px;
        font-size: 14px;
        display: none;
    }
    
    .stats-section {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
        gap: 20px;
        margin-top: 20px;
    }
    
    .stat-card {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        color: white;
        padding: 20px;
        border-radius: 10px;
        text-align: center;
    }
    
    .stat-card h4 {
        font-size: 14px;
        margin-bottom: 10px;
        opacity: 0.9;
    }
    
    .stat-card .number {
        font-size: 28px;
        font-weight: bold;
    }
    
    .format-example {
        background: #fff3cd;
        border: 1px solid #ffeaa7;
        border-radius: 8px;
        padding: 15px;
        margin-top: 20px;
        font-size: 14px;
    }
    
    .format-example h4 {
        color: #856404;
        margin-bottom: 10px;
    }
    
    .format-table {
        width: 100%;
        border-collapse: collapse;
        margin-top: 10px;
        font-size: 12px;
    }
    
    .format-table th,
    .format-table td {
        border: 1px solid #ddd;
        padding: 6px 8px;
        text-align: center;
    }
    
    .format-table th {
        background: #f8f9fa;
        font-weight: bold;
    }
</style>
{% endblock %}

{% block content %}
<div class="container dashboard-container">
    <div class="dashboard-header">
        <div class="header">
            <h1>📊 管理后台</h1>
            <p>Excel数据管理系统</p>
        </div>
        <a href="/admin/logout" class="logout-btn">退出登录</a>
    </div>
    
    <div class="alert"></div>
    
    <div class="upload-section">
        <h3>📁 上传Excel文件</h3>
        
        <form id="uploadForm" enctype="multipart/form-data">
            <div class="file-input-wrapper">
                <input type="file" id="excelFile" name="file" accept=".xlsx,.xls" class="file-input" required>
                <label for="excelFile" class="file-input-display">
                    📎 点击选择Excel文件 (.xlsx, .xls)
                </label>
            </div>
            
            <div id="fileInfo" class="file-info"></div>
            
            <button type="submit" class="btn">🚀 上传并解析</button>
        </form>
        
        <div class="format-example">
            <h4>📋 Excel文件格式要求：</h4>
            <p>• 第一行：标题（如：高一第一次小测试）</p>
            <p>• 第二行：字段名（班级、姓名、各科目名称）</p>
            <p>• 第三行开始：学生数据</p>
            
            <table class="format-table">
                <tr>
                    <th colspan="6">高一第一次小测试</th>
                </tr>
                <tr>
                    <th>班级</th>
                    <th>姓名</th>
                    <th>语文</th>
                    <th>数学</th>
                    <th>英语</th>
                    <th>物理</th>
                </tr>
                <tr>
                    <td>2025级1班</td>
                    <td>安冉</td>
                    <td>54</td>
                    <td></td>
                    <td>107.5</td>
                    <td>77</td>
                </tr>
                <tr>
                    <td>2025级1班</td>
                    <td>陈慧茹</td>
                    <td>67</td>
                    <td></td>
                    <td>91</td>
                    <td>79</td>
                </tr>
            </table>
        </div>
    </div>
    
    <div class="stats-section" id="statsSection">
        <!-- 统计信息将通过JavaScript动态加载 -->
    </div>
    
    <div style="margin-top: 30px; text-align: center;">
        <a href="/" style="color: #667eea; text-decoration: none;">← 返回查询页面</a>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
// 文件选择处理
document.getElementById('excelFile').addEventListener('change', function(e) {
    const file = e.target.files[0];
    const fileInfo = document.getElementById('fileInfo');
    
    if (file) {
        const fileSize = (file.size / 1024 / 1024).toFixed(2);
        fileInfo.innerHTML = `
            <strong>已选择文件：</strong>${file.name}<br>
            <strong>文件大小：</strong>${fileSize} MB<br>
            <strong>文件类型：</strong>${file.type}
        `;
        fileInfo.style.display = 'block';
    } else {
        fileInfo.style.display = 'none';
    }
});

// 表单提交处理
document.getElementById('uploadForm').addEventListener('submit', async function(e) {
    e.preventDefault();
    
    const fileInput = document.getElementById('excelFile');
    const file = fileInput.files[0];
    
    if (!file) {
        showAlert('请选择Excel文件');
        return;
    }
    
    const formData = new FormData();
    formData.append('file', file);
    
    try {
        // 显示上传中状态
        const submitBtn = document.querySelector('button[type="submit"]');
        const originalText = submitBtn.textContent;
        submitBtn.textContent = '📤 上传中...';
        submitBtn.disabled = true;
        
        const response = await fetch('/api/upload_excel', {
            method: 'POST',
            body: formData
        });
        
        const data = await response.json();
        
        if (data.success) {
            showAlert(data.message, 'success');
            fileInput.value = '';
            document.getElementById('fileInfo').style.display = 'none';
            loadStats(); // 重新加载统计信息
        } else {
            showAlert(data.message);
        }
        
        // 恢复按钮状态
        submitBtn.textContent = originalText;
        submitBtn.disabled = false;
        
    } catch (error) {
        showAlert('上传失败，请稍后重试');
        console.error('Error:', error);
        
        // 恢复按钮状态
        const submitBtn = document.querySelector('button[type="submit"]');
        submitBtn.textContent = '🚀 上传并解析';
        submitBtn.disabled = false;
    }
});

// 加载统计信息
async function loadStats() {
    try {
        const classesResponse = await fetch('/api/get_all_classes');
        const classesData = await classesResponse.json();
        
        let totalStudents = 0;
        if (classesData.success && classesData.classes.length > 0) {
            // 计算总学生数
            for (const className of classesData.classes) {
                const studentsResponse = await fetch(`/api/get_class_students/${encodeURIComponent(className)}`);
                const studentsData = await studentsResponse.json();
                if (studentsData.success) {
                    totalStudents += studentsData.student_count;
                }
            }
        }
        
        const statsHtml = `
            <div class="stat-card">
                <h4>📚 班级总数</h4>
                <div class="number">${classesData.success ? classesData.classes.length : 0}</div>
            </div>
            <div class="stat-card">
                <h4>👥 学生总数</h4>
                <div class="number">${totalStudents}</div>
            </div>
            <div class="stat-card">
                <h4>📊 数据状态</h4>
                <div class="number">${totalStudents > 0 ? '✅' : '❌'}</div>
            </div>
        `;
        
        document.getElementById('statsSection').innerHTML = statsHtml;
        
    } catch (error) {
        console.error('Failed to load stats:', error);
    }
}

// 页面加载时获取统计信息
loadStats();
</script>
{% endblock %}